<template>
  <div class="building-manager-container">
    <el-form :model="searchForm" :rules="rules" ref="searchFormRef" label-width="80px">
      <div class="search-container">
        <el-form-item label="字段：" prop="key" class="search-field">
          <el-select 
            v-model="searchForm.key" 
            placeholder="请选择字段"
            style="width: 180px"
          >
            <el-option label="楼号" value="name"></el-option>
            <el-option label="学院" value="introduction"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="值：" class="search-value">
          <el-input 
            v-model="searchForm.value" 
            placeholder="请输入关键字"
            style="width: 180px"
          />
          <el-button 
            type="primary" 
            icon="Search"
            @click="handleSearch"
            style="margin-left: 10px"
          >
            搜索
          </el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="230" fixed />
      <el-table-column prop="name" label="楼号" width="230" />
      <el-table-column prop="introduction" label="学院" width="230" />
      <el-table-column prop="adminName" label="管理员" width="230" />
      <el-table-column label="操作" width="230" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      v-model:current-page="pagination.currentPage"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { buildingApi } from '@/api/buildings'  // 修改为从您的index.js导入

const router = useRouter()
const searchFormRef = ref(null)

// 搜索表单
const searchForm = ref({
  key: 'name',
  value: '',
})

// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 3,
  total: 0
})

// 表格数据
const tableData = ref([])

// 验证规则
const rules = {
  key: [
    { required: true, message: '请选择字段', trigger: 'change' }
  ]
}

// 获取楼宇列表
const fetchBuildings = async () => {
  try {
    const { currentPage, pageSize } = pagination.value
    const res = await buildingApi.getBuildingList(currentPage, pageSize)
    tableData.value = res.data.data  // 根据您的接口结构调整
    pagination.value.total = res.data.total
  } catch (error) {
    ElMessage.error('获取楼宇列表失败: ' + error.message)
  }
}

// 搜索楼宇
const handleSearch = async () => {
  try {
    pagination.value.currentPage = 1
    
    if (!searchForm.value.value) {
      await fetchBuildings()
      return
    }

    const params = {
      key: searchForm.value.key,
      value: searchForm.value.value,
      page: pagination.value.currentPage,
      size: pagination.value.pageSize
    }

    const res = await buildingApi.searchBuildings(params)
    tableData.value = res.data.data
    pagination.value.total = res.data.total
  } catch (error) {
    ElMessage.error('搜索失败: ' + error.message)
  }
}

// 分页变化
const handlePageChange = async (page) => {
  pagination.value.currentPage = page
  if (!searchForm.value.value) {
    await fetchBuildings()
  } else {
    await handleSearch()
  }
}

// 编辑楼宇
const handleEdit = (row) => {
  router.push(`/buildingUpdate?id=${row.id}`)
}

// 删除楼宇
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await buildingApi.deleteBuilding(row.id)
    if (res.code === 0) {  // 根据您的接口结构调整
      ElMessage.success(`【${row.name}】已删除`)
      if (tableData.value.length === 1 && pagination.value.currentPage > 1) {
        pagination.value.currentPage -= 1
      }
      await handlePageChange(pagination.value.currentPage)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 初始化
onMounted(() => {
  fetchBuildings()
})
</script>

<style scoped>
.building-manager-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-field {
  margin-right: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>